import React, { Component } from 'react';
import { LeftOutlined, RightOutlined } from '@ant-design/icons'
import moment from 'moment'
import './style.less'
export default class Calendar extends Component {
    constructor() {
        super()
        this.formRef = React.createRef()
        this.state = {
            visible: false,
            weekDayNum: 7,
            today_date: moment(new Date()).format("yyyy-MM-DD"),
            daysOfMonth: [],
            current_date: moment(new Date()).format("yyyy-MM"),
            current_day: moment(new Date()).format("DD"),
            checkDay: '',
            // 日历头部
            calendar_head: ["日", "一", "二", "三", "四", "五", "六"],
            weekday: ["一", "二", "三", "四", "五", "六", "日"],

        }

    }
    componentDidMount() {
        this.setState({
            daysOfMonth: this.getCalendarAllDays(this.current_date)
        }, () => {
            console.log(this.state.daysOfMonth, 'daysOfMonth')
        })
    }
    // 获取当前月份日历所有日期
    createMonthDay = (stime, etime) => {
        //初始化日期列表，数组
        let diffdate = new Array();
        let i = 0;
        //开始日期小于等于结束日期,并循环
        while (stime <= etime) {
            diffdate[i] = stime;

            //获取开始日期时间戳
            let stime_ts = new Date(stime).getTime();
            // console.log("当前日期：" + stime + "当前时间戳：" + stime_ts);

            //增加一天时间戳后的日期
            let next_date = stime_ts + 24 * 60 * 60 * 1000;

            //拼接年月日，这里的月份会返回（0-11），所以要+1
            let next_dates_y = new Date(next_date).getFullYear() + "-";
            let next_dates_m =
                new Date(next_date).getMonth() + 1 < 10
                    ? "0" + (new Date(next_date).getMonth() + 1) + "-"
                    : new Date(next_date).getMonth() + 1 + "-";
            let next_dates_d =
                new Date(next_date).getDate() < 10
                    ? "0" + new Date(next_date).getDate()
                    : new Date(next_date).getDate();

            stime = next_dates_y + next_dates_m + next_dates_d;

            //增加数组key
            i++;
        }
        return diffdate;
    };
    getWeekDays = (date) => {
        let oneDayTime = 1000 * 60 * 60 * 24;
        let today = new Date(date);
        // 若那一天是周末时，则强制赋值为7
        let todayDay = today.getDay() || 7;
        let startDate = new Date(today.getTime() - oneDayTime * (todayDay - 1));
        let dateList = new Array();
        for (let i = 0; i < 7; i++) {
            let temp = new Date(startDate.getTime() + i * oneDayTime);
            let year = temp.getFullYear();
            let month =
                temp.getMonth() + 1 < 10
                    ? "0" + (temp.getMonth() + 1)
                    : temp.getMonth() + 1;
            let day = temp.getDate() < 10 ? "0" + temp.getDate() : temp.getDate();
            dateList[i] = `${year}-${month}-${day}`;
        }
        return dateList;
    };
    getFirstAndLastDay = (date) => {
        let now = date ? new Date(date) : new Date(); //当前日期
        let nowMonth = now.getMonth(); //当前月
        let nowYear = now.getFullYear(); //当前年
        //本月的开始时间
        let monthStartDate = new Date(nowYear, nowMonth, 1);
        //本月的结束时间
        let monthEndDate = new Date(nowYear, nowMonth + 1, 0);
        let timeStar = moment(Date.parse(monthStartDate)).format("yyyy-MM-DD"); //s
        let timeEnd = moment(Date.parse(monthEndDate)).format("yyyy-MM-DD"); //s
        return [timeStar, timeEnd];
    };
    getNextDate = (date, day) => {
        let dd = new Date(date);
        dd.setDate(dd.getDate() + day);
        let y = dd.getFullYear();
        let m =
            dd.getMonth() + 1 < 10 ? "0" + (dd.getMonth() + 1) : dd.getMonth() + 1;
        let d = dd.getDate() < 10 ? "0" + dd.getDate() : dd.getDate();
        return y + "-" + m + "-" + d;
    };
    getNextWeek = (date, len) => {
        let times = [];
        for (let i = 0; i <= len; i++) {
            times.push(moment(date).add(i, "d").format("yyyy-MM-DD"));
        }
        return times;
    };
    getCalendarAllDays = (date) => {
        let time = [];
        let startAndEnd = this.getFirstAndLastDay(date);
        let firstWeek = this.getWeekDays(startAndEnd[0]),
            lastWeek = this.getWeekDays(startAndEnd[1]),
            currentMonthDays = this.createMonthDay(startAndEnd[0], startAndEnd[1]);

        firstWeek.unshift(this.getNextDate(firstWeek[0], -1));
        // 如果一号是周日
        if (new Date(startAndEnd[0]).getDay() == 0) {
            time = Array.from(new Set([...currentMonthDays, ...lastWeek]));
        } else {
            time = Array.from(
                new Set([...firstWeek, ...currentMonthDays, ...lastWeek])
            );
        }
        let nextWeeks = [];
        if (time.length < 42) {
            nextWeeks = this.getNextWeek(time[time.length - 1], 42 - time.length);
            time = Array.from(new Set([...time, ...nextWeeks]));
        } else {
            time = time.splice(0, 42);
        }
        return time;
    };

    getNextMonth = (date, addMonths) => {
        let dd = new Date(date);
        let m = dd.getMonth() + 1;
        let y =
            dd.getMonth() + 1 + addMonths > 12
                ? dd.getFullYear() + 1
                : dd.getFullYear();
        if (m + addMonths == 0) {
            y = y - 1;
            m = 12;
        } else {
            if (m + addMonths > 12) {
                m = "01";
            } else {
                m = m + 1 < 10 ? "0" + (m + addMonths) : m + addMonths;
            }
        }
        return y + "-" + m;
    };

    prevMonth = () => {
        const { current_date } = this.state
        let date = moment(this.getNextMonth(current_date, -1)).format("yyyy-MM");
        this.setState({
            current_date: date,
            daysOfMonth: this.getCalendarAllDays(date)
        })
    };
    nextMonth = () => {
        const { current_date } = this.state
        let date = moment(this.getNextMonth(current_date, 1)).format("yyyy-MM");
        console.log(date, 'date');
        this.setState({
            current_date: date,
            daysOfMonth: this.getCalendarAllDays(date)
        })
    };
    check = (time) => {
        console.log(time, '111111');
        this.props.checkDay(time)
        this.setState({
            checkDay: time

        })
        return false
        const { today_date } = this.state
        let other =
            moment(time).format("MM") !== today_date.split("-")[1];
        let day = moment(time).format("DD");
        if (!other) {
            this.setState({
                checkDay: day,
                visible: true,
            })
        }
    };
    getMark = (time) => {
        const { current_day } = this.state

        let date = moment(time).format("DD");
        if (date > current_day) {
            // // 判断是否存在排班
            // //console.log(props.hasShiftDateStr, "peops.hasShiftDateStr", time);
            // if (props.hasShiftDateStr?.includes(time)) {
            //     return "background:#ffb321;box-shadow: 0px 0px 11px 1px rgba(255, 179, 33, 0.6);";
            // } else {
            //     return "display:none";
            // }
        } else if (date < current_day) {
            return "background:#2A70E9;box-shadow: 0px 0px 11px 1px rgba(42, 112, 233, 0.6);";
        } else {
            return "background:#00ff00;box-shadow: 0px 0px 11px 1px rgba(0, 255, 0, 0.6);";
        }
    };
    getTodayBc = (time) => {
        const { current_day } = this.state
        let date = moment(time).format("DD");

        if (date == current_day) {
            return "background:#011956";
        }
    };


    onChange = (date, dateString) => {
        this.setState({
            current_date: dateString,
            today_date: dateString,
            daysOfMonth: this.getCalendarAllDays(dateString)
        }, () => {
            console.log(this.state.daysOfMonth, 'daysOfMonth')
        })
    }


    render() {
        const { lightHighDays } = this.props
        const { visible, today_date, current_date, checkDay, current_day, calendar_head, daysOfMonth, weekDayNum } = this.state
        return (
            <div className=" calendarBox">
                <div className='utils '>
                    <div className="left" onClick={this.prevMonth}><LeftOutlined /></div>
                    <div>{current_date}</div>
                    <div className="right" onClick={this.nextMonth}><RightOutlined /></div>
                </div>
                <div className="calendar">
                    <div className="head">

                        {
                            calendar_head.map((item, index) => <div key={index + 'head'} className="col">{item}</div>)
                        }

                    </div>
                    <div className="body">
                        {
                            Array.from(new Array(Math.ceil(daysOfMonth.length / 7)).keys()).map((week, week_index) => {
                                return (
                                    <div className="row" key={'week' + week_index}>
                                        {
                                            Array.from(new Array(weekDayNum).keys()).map((day, day_index) => {
                                                return (
                                                    <div
                                                        key={'day' + day_index}
                                                        // style={this.getTodayBc(daysOfMonth[week_index * weekDayNum + day_index])}
                                                        className={
                                                            ['col',
                                                                moment(daysOfMonth[week_index * weekDayNum + day_index]).format('MM') !==
                                                                    current_date.split('-')[1] ||
                                                                    moment(daysOfMonth[week_index * weekDayNum + day_index]).format(
                                                                        'yyyy'
                                                                    ) !== today_date.split('-')[0] ||
                                                                    moment(today_date).format('MM') !== current_date.split('-')[1] ? 'otherMonth' : '',

                                                                lightHighDays && lightHighDays.includes(moment(daysOfMonth[week_index * weekDayNum + day_index]).format('yyy-MM-DD'))
                                                                    ? "checkLow" : '',
                                                                checkDay == daysOfMonth[week_index * weekDayNum + day_index]
                                                                    ? "checkHigh" : ''

                                                            ].join(' ')
                                                        }
                                                        onClick={() => this.check(daysOfMonth[week_index * weekDayNum + day_index])}
                                                    >

                                                        <div className='riqi' key={'riqi' + week_index}>
                                                            {moment(daysOfMonth[week_index * weekDayNum + day_index]).format("DD")}
                                                        </div>
                                                    </div>
                                                )
                                            })
                                        }
                                    </div>
                                )
                            })
                        }
                    </div>
                </div >

            </div >
        );
    }
}
